var Data = {};

app.controller('TakedTaskCtrl', function($scope) {
	var needNewPagination = true;
	
	var pageNo = 1;
	var statesArray = "101,111,112,113,200,201,211,212,213,221,310,-1";
	requestData();
	//每隔60秒钟刷新一次任务
	setInterval(function() {
		requestData();
	}, 60*1000);
	
	RemainTime();
	
	/*
	请求数据
	*/
	function requestData() {
		var searchProp = $("#search-task").siblings("input.input1").val();
		var param = {
			pageNo: pageNo,
			pageCount: 10,
			statesArray: statesArray,
			searchProp: searchProp,
			orderType: 2,
		};
		AQ.callAQJSON("getTakedTask.do", param, function(jsonData) {
			var result = jsonData.data;
			var data = [];
			for (var i = 0; i < result.length; i++) {
				data.push({
					taskObj: setDoingTaskObj(result[i]),
					taskId: result[i].taskId,
					takeTime: result[i].takeTime.substr(5),
					sellerNick: result[i].sellerNick,
					searchType: DIC.SearchType[result[i].searchType],
					modifyPrice: DIC.TrueFalse(result[i].modifyPrice),
					phoneOrder: DIC.PhoneOrder[result[i].phoneOrder],
					orderText: result[i].phoneOrder == 0 ? "电脑访问" : "手机访问",
					rateTime: DIC.RateTime[result[i].rateTime],
					noWordRate: DIC.TrueFalse(result[i].noWordRate),
					checkBuyerIp: DIC.TrueFalse(result[i].checkBuyerIp),
					takeArea: DIC.IsShow(result[i].takeArea),
					rankLimit: result[i].rankLimit,
					realName: DIC.TrueFalse(result[i].realName),
					checkTaker: DIC.TrueFalse(result[i].checkTaker),
					compare: DIC.TrueFalse(result[i].compare),
					browseOthers: DIC.TrueFalse(result[i].browseOthers),
					collect: DIC.TrueFalse(result[i].collect),
					stayTime: DIC.TrueFalse(result[i].stayTime),
					talk: DIC.TrueFalse(result[i].talk),
					browseFoot: DIC.TrueFalse(result[i].browseFoot),
					productLink: result[i].productLink,
					proLink_isShow: proLinkIsShow(result[i].state, result[i].searchType) || result[i].state == -1,
					userName: result[i].userName,
					buyerNick: result[i].buyerNick,
					tellTaker: result[i].tellTaker,
					tellTaker_isShow: DIC.IsShow(result[i].tellTaker),
					feibi: Utils.formatMoney(result[i].feibi),
					realYongjin: Utils.formatMoney(0.75 * result[i].feibi),
					totalMoney: Utils.formatMoney(result[i].totalMoney),
					price: Utils.formatMoney(result[i].price),
					amount: result[i].amount,
					state: DIC.ExplaStateVisit[result[i].state],
					taskDetail_isShow: (result[i].state >= 320 || result[i].state == -1) ? true : false,
					cancel_isShow: result[i].state <= 310 ? true : false,
					qq: result[i].qq,
					takerNote: result[i].takerNote,
					doBtShow: DIC.DoBtShowT(result[i].state),
					doText: "处理任务",
					remainSeconds: result[i].remainSeconds,
					remainSeconds_isShow: DIC.TrueFalse(result[i].remainSeconds),
				});
			}
			$scope.$apply(function () {
				$scope.taskList = data;
				addZclip();
				if(pageNo == 1 && needNewPagination) {	//创建分页
					var num_entries = jsonData.size;
					Utils.newPagination("Pagination", num_entries, function(page_index, jq) {
						if(page_index == 0 && needNewPagination) {
							needNewPagination = false;
							return;
						}
						pageNo = page_index + 1;
						requestData();
					});
				}
			});
		}, function(err, code) {
			console.log(err + "["+ code +"]");
		});
	}
	
	/**
	显示剩余时间
	
	@param remainSeconds
	*/
	function RemainTime(){
		setInterval(function(){
			$(".time-item").each(function(index, element) {
				var intDiff = parseInt($(element).attr("second"));
				var day=0, hour=0, minute=0, second=0;	//时间默认值
				if(intDiff > 0){
					day = Math.floor(intDiff / (60 * 60 * 24));
					hour = Math.floor(intDiff / (60 * 60)) - (day * 24);
					minute = Math.floor(intDiff / 60) - (day * 24 * 60) - (hour * 60);
					second = Math.floor(intDiff) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);
					
					intDiff--;
					$(element).attr('second',intDiff);
					
					if (hour <= 9) hour = '0' + hour;
					if (minute <= 9) minute = '0' + minute;
					if (second <= 9) second = '0' + second;
					$(element).find('#day_show').html(day+"天");
					$(element).find('#hour_show').html('<s id="h"></s>'+hour+':');
					$(element).find('#minute_show').html('<s></s>'+minute+':');
					$(element).find('#second_show').html('<s></s>'+second);
				}
				//倒计时到1时，3S后刷新任务
				if(intDiff == 1) {
					setTimeout(function(){
						requestData();
					}, 3000);
				}
			});
		}, 1000);
	}
	
	//查看任务详情
	$scope.taskDetail = function(taskId, buyerNick) {
		var param = {
			taskId: taskId,
			userType: 2,
		};
		AQ.callAQ("getTaskDetail.do", param, function(result) {
			var compare1Link = result[1].compare1Link;
			var compare2Link = result[1].compare2Link;
			var compare3Link = result[1].compare3Link;
			var lookRatePic = result[1].lookRatePic;
			var lookSalesPic = result[1].lookSalesPic;
			var centerPic = result[1].centerPic;
			var collectPic = result[1].collectPic;
			var browse1Link = result[1].browse1Link;
			var browse2Link = result[1].browse2Link;
			var browse3Link = result[1].browse3Link;
			var collectShopPic = result[1].collectShopPic;
			var talkPic = result[1].talkPic;
			var rateSuccessPic = result[1].rateSuccessPic;
			var bottomPic = result[1].bottomPic;
			var region = result[1].region;
			var city = result[1].city;
			var ip = result[1].ip.length > 16 ? "" : result[1].ip;
			var payTime = result[1].payTime;
			var rateTime = result[1].rateTime;
			var finishTime = result[1].finishTime;
			
			var compareHtml='', collectHtml='', browseHtml='', talkHtml='', rateSuccessHtml='', rateHtml='', bottomHtml='';
			if(!(compare1Link == "" && compare2Link == "" && compare3Link == "")) {
				compareHtml = '<div style="border-top:1px solid #72819D; margin:20px 10px 0 10px; padding-bottom:20px; font-size:14px;">'+
					'<div style="width:120px; height:30px; border-top:3px solid #72819D; text-align:center; font-weight:bold; color:#546178;">货比三家截图</div>';
				if(compare1Link != "") {
					compareHtml += '<a href="'+ compare1Link +'" target="_blank"><img width="250px" src="'+ compare1Link +'"></a>&nbsp;';
				}
				if(compare2Link != "") {
					compareHtml += '<a href="'+ compare2Link +'" target="_blank"><img width="250px" src="'+ compare2Link +'"></a>&nbsp;';
				}
				if(compare3Link != "") {
					compareHtml += '<a href="'+ compare3Link +'" target="_blank"><img width="250px" src="'+ compare3Link +'"></a>';
				}
				compareHtml += '</div>';
			}
			if(!(lookRatePic == "" && lookSalesPic == "")) {
				rateHtml= '<div style="border-top:1px solid #72819D; margin:20px 10px 0 10px; padding-bottom:20px; font-size:14px;">'+
					'<div style="width:120px; height:30px; border-top:3px solid #72819D; text-align:center; font-weight:bold; color:#546178;">查看评价/销量截图</div>';
				if(lookRatePic != "") {
					rateHtml += '<a href="'+ lookRatePic +'" target="_blank"><img width="250px" src="'+ lookRatePic +'"></a>&nbsp;';
				}
				if(lookSalesPic != "") {
					rateHtml += '<a href="'+ lookSalesPic +'" target="_blank"><img width="250px" src="'+ lookSalesPic +'"></a>';
				}
				rateHtml += '</div>';
			}
			if(!(bottomPic == "" && centerPic == "")) {
				bottomHtml= '<div style="border-top:1px solid #72819D; margin:20px 10px 0 10px; padding-bottom:20px; font-size:14px;">'+
					'<div style="width:120px; height:30px; border-top:3px solid #72819D; text-align:center; font-weight:bold; color:#546178;">宝贝详情中/下截图</div>';
				if(centerPic != "") {
					bottomHtml += '<a href="'+ centerPic +'" target="_blank"><img width="250px" src="'+ centerPic +'"></a>&nbsp;';
				}
				if(bottomPic != "") {
					bottomHtml += '<a href="'+ bottomPic +'" target="_blank"><img width="250px" src="'+ bottomPic +'"></a>';
				}
				bottomHtml += '</div>';
			}
			if(!(collectPic == "" && collectShopPic == "")) {
				collectHtml = '<div style="border-top:1px solid #72819D; margin:20px 10px 0 10px;  padding-bottom:20px; font-size:14px;">'+
					'<div style="width:120px; height:30px; border-top:3px solid #72819D; text-align:center; font-weight:bold; color:#546178;">收藏截图</div>';
				if(collectPic != "") {
					collectHtml += '<a href="'+ collectPic +'" target="_blank"><img width="250px" src="'+ collectPic +'"></a>&nbsp;';
				}
				if(collectShopPic != "") {
					collectHtml += '<a href="'+ collectShopPic +'" target="_blank"><img width="250px" src="'+ collectShopPic +'"></a>';
				}
				collectHtml += '</div>';
			}
			if(!(browse1Link == "" && browse2Link == "" && browse3Link == "")) {
				browseHtml = '<div style="border-top:1px solid #72819D; margin:20px 10px 0 10px;  padding-bottom:20px; font-size:14px;">'+
					'<div style="width:120px; height:30px; border-top:3px solid #72819D; text-align:center; font-weight:bold; color:#546178;">店铺宝贝浏览截图</div>';
				if(browse1Link != "") {
					browseHtml += '<a href="'+ browse1Link +'" target="_blank"><img width="250px" src="'+ browse1Link +'"></a>&nbsp;';
				}
				if(browse2Link != "") {
					browseHtml += '<a href="'+ browse2Link +'" target="_blank"><img width="250px" src="'+ browse2Link +'"></a>&nbsp;';
				}
				if(browse3Link != "") {
					browseHtml += '<a href="'+ browse3Link +'" target="_blank"><img width="250px" src="'+ browse3Link +'"></a>';
				}
				browseHtml += '</div>';
			}
			if(talkPic != "") {
				talkHtml = '<div style="border-top:1px solid #72819D; margin:20px 10px 0 10px; padding-bottom:20px; font-size:14px;">'+
					'<div style="width:120px; height:30px; border-top:3px solid #72819D; text-align:center; font-weight:bold; color:#546178;">聊旺旺截图</div>';
				talkHtml += '<a href="'+ talkPic +'" target="_blank"><img width="250px" src="'+ talkPic +'"></a>';
				talkHtml += '</div>';
			}
			if(rateSuccessPic != "") {
				rateSuccessHtml = '<div style="border-top:1px solid #72819D; margin:20px 10px 0 10px; padding-bottom:20px; font-size:14px;">'+
					'<div style="width:120px; height:30px; border-top:3px solid #72819D; text-align:center; font-weight:bold; color:#546178;">五分好评截图</div>';
				rateSuccessHtml += '<a href="'+ rateSuccessPic +'" target="_blank"><img width="250px" src="'+ rateSuccessPic +'"></a>';
				rateSuccessHtml += '</div>';
			}
			
			var content = '<div id="taskDetailDialog" style="width:800px; height:450px; overflow:auto; border:1px solid #DDDDDD; font-family:Microsoft YaHei;">'+
					'<div style="background:#72819D; padding:15px 20px;">'+
					'<span style="font-size:15px; color:#FFF;">任务编号：'+ taskId +'</span>'+
					'<div style="padding-left:30px; padding-top:5px;">'+
					'<span style="font-size:12px; color:#FFF;">付款时间：'+ payTime +'</span>'+
					'<span style="font-size:12px; color:#FFF; padding-left:50px;">评价时间：'+ rateTime +'</span>'+
					'<span style="font-size:12px; color:#FFF; padding-left:50px;">放款时间：'+ finishTime +'</span></div>'+
					'<div style="height:30px; line-height:30px; padding-left:35px; margin-top:10px; color:#FFF; font-size:18px; background:url(images/icon/bd_ww.png) no-repeat;">'+ buyerNick +
					'<span style="font-size:13px; margin-left:40px;">'+ region +'&nbsp;'+ city +'&nbsp;&nbsp;&nbsp;'+ ip +'</span>'+
					'</div>'+
					'</div>'
					+ compareHtml + bottomHtml + rateHtml + collectHtml + browseHtml + talkHtml + rateSuccessHtml +
					'</div>';
			taskDetailDialog(content);
		}, function(err, code) {
			Utils.msgDialog(err + "["+ code +"]");
		});
	};
	
	$scope.qqTalk = function(qq) {
		var content = '对方QQ号：<span style="color:#F50; font-weight:bold;">'+ qq +'</span><BR>'+
				'临时会话可能会收不到消息，建议把对方加为好友。';
		Utils.checkDialog(content, "确定", "取消",
			function() {
				location.replace("tencent://message/?uin="+ qq +"&Site=qq&Menu=yes");
			}, function() {}
		);
	};
	
	$scope.noteTask = function(taskId, taskNote) {
		$("#note_"+ taskId).each(function(index, element) {
        	$(element).remove();
		});
		var content = '<textarea id="note_'+ taskId +'" style="width:340px; height:150px; resize:none; border:1px solid #E5E5E5; padding:5px;">'+ taskNote +'</textarea>';
		var d = dialog({
				fixed: true,
				zIndex: 999999999,
				title: '添加备注',
				content: content,
				okValue: '保存',
				cancelValue: '返回',
				ok: function() {
					taskNote = $.trim($("#note_"+taskId).val());
					var param = {
						taskId: taskId,
						taskNote: taskNote,
						userType: 2,
					};
					AQ.callAQ("takerNoteTask.do", param, function(result) {
						requestData();
					}, function(err, code) {
						Utils.msgDialog(err + "["+ code +"]");
					});
				}, cancel: function() {}
		});
		d.width(350);
		d.showModal();
	};
	
	$scope.lookRatePic = function(ratePic1, ratePic2, ratePic3, ratePic4, ratePic5) {
		var content = '<div id="ratePicDialog" style="width:600px; height:400px; overflow:auto; border:1px solid #DDDDDD; padding:5px; font-family:Microsoft YaHei;">';
		var picNo = 0;
		if(ratePic1 != "") {
			picNo ++;
			content += '<div style="background:#72819D; width:35px; height:35px; line-height:35px; border-radius:18px; display:inline-block; text-align:center; color:#FFF;">'+ picNo +'</div><div style="border-bottom:2px solid #72819D; width:90%; display:inline-block;"></div>'+
			'<div style="padding:20px 0;"><a href="'+ ratePic1 +'" target="_blank"><img width="580px" src="'+ ratePic1 +'"></a></div>';
		}
		if(ratePic2 != "") {
			picNo ++;
			content += '<div style="background:#72819D; width:35px; height:35px; line-height:35px; border-radius:18px; display:inline-block; text-align:center; color:#FFF;">'+ picNo +'</div><div style="border-bottom:2px solid #72819D; width:90%; display:inline-block;"></div>'+
			'<div style="padding:20px 0;"><a href="'+ ratePic2 +'" target="_blank"><img width="580px" src="'+ ratePic2 +'"></a></div>';
		}
		if(ratePic3 != "") {
			picNo ++;
			content += '<div style="background:#72819D; width:35px; height:35px; line-height:35px; border-radius:18px; display:inline-block; text-align:center; color:#FFF;">'+ picNo +'</div><div style="border-bottom:2px solid #72819D; width:90%; display:inline-block;"></div>'+
			'<div style="padding:20px 0;"><a href="'+ ratePic3 +'" target="_blank"><img width="580px" src="'+ ratePic3 +'"></a></div>';
		}
		if(ratePic4 != "") {
			picNo ++;
			content += '<div style="background:#72819D; width:35px; height:35px; line-height:35px; border-radius:18px; display:inline-block; text-align:center; color:#FFF;">'+ picNo +'</div><div style="border-bottom:2px solid #72819D; width:90%; display:inline-block;"></div>'+
			'<div style="padding:20px 0;"><a href="'+ ratePic4 +'" target="_blank"><img width="580px" src="'+ ratePic4 +'"></a></div>';
		}
		if(ratePic5 != "") {
			picNo ++;
			content += '<div style="background:#72819D; width:35px; height:35px; line-height:35px; border-radius:18px; display:inline-block; text-align:center; color:#FFF;">'+ picNo +'</div><div style="border-bottom:2px solid #72819D; width:90%; display:inline-block;"></div>'+
			'<div style="padding:20px 0;"><a href="'+ ratePic5 +'" target="_blank"><img width="580px" src="'+ ratePic5 +'"></a></div>';
		}
		content += '</div>';
		ratePicDialog(content);
	};
	
	//取消任务
	$scope.cancelTakedTask = function(taskId) {
		Utils.checkDialog("确定取消任务吗？", "确定", "返回",
			function() {
				var param = {
					taskId: taskId,
					orderType: 2,
				};
				AQ.callAQ("cancelTakedTask.do", param, function(result) {
					requestData();
				}, function(err, code) {
					Utils.msgDialog(err + "["+ code +"]");
				});
			}, function() {}
		);
	};
	
	/**
	点击处理任务按钮
	
	@param taskObj {String}
	*/
	$scope.handleTask = function(taskObj) {
		var obj = JSON.parse(taskObj);
		if(obj.state >= 111 && obj.state <= 310) {
			$.base64.utf8encode = true;
			var encodeObj = $.base64.encode(taskObj);
			if(obj.phoneOrder == 0) {
				window.open("doing-take.html?taskObj=" + encodeObj);
			} else if(obj.phoneOrder == 1) {
				window.open("doing-take-phone.html?taskObj=" + encodeObj);
			}
		} else if(obj.state == 3100) {
			var content = '请您确认<span style="color:#F82800;">已在淘宝给出好评</span>，被放单人投诉会受处罚。'+
					'<span style="color:#666666;">（按照放单人的规定给好评、晒图）</span>';
			Utils.checkDialog(content, "确定", "取消", 
				function() {
					var param = {
						taskId: obj.taskId,
					};
					AQ.callAQ("confirmReceive.do", param, function(result) {
						requestData();
					}, function(err, code) {
						Utils.msgDialog(err + "["+ code +"]");
					});
				}, function() {}
			);
		}
	}
	
	//可处理任务
	$("#states-filter-1").click(function() {
		$("#search-task").siblings("input.input1").val("");
		statesArray = "101,111,112,113,200,201,211,212,213,221,310,-1";
		pageNo = 1;
		needNewPagination = true;
		location.hash = "#go-to-sign";
		requestData();
    });
	//待放款任务
	$("#states-filter-3").click(function() {
		$("#search-task").siblings("input.input1").val("");
		statesArray = "320";
		pageNo = 1;
		needNewPagination = true;
		location.hash = "#go-to-sign";
		requestData();
    });
	//已完成任务
	$("#states-filter-4").click(function() {
		$("#search-task").siblings("input.input1").val("");
		statesArray = "400";
		pageNo = 1;
		needNewPagination = true;
		location.hash = "#go-to-sign";
		requestData();
    });
	//全部任务
	$("#states-filter-5").click(function() {
		$("#search-task").siblings("input.input1").val("");
		statesArray = "101,111,112,113,200,201,211,212,213,221,310,320,400,-1";
		pageNo = 1;
		needNewPagination = true;
		location.hash = "#go-to-sign";
		requestData();
    });
	
	//点击刷新
	$("#shuaxin-task").click(function() {
		pageNo = 1;
		needNewPagination = true;
		location.hash = "#go-to-sign";
        requestData();
    });
	
	//点击搜索任务
	$("#search-task").click(function() {
		pageNo = 1;
		needNewPagination = true;
		location.hash = "#go-to-sign";
        requestData();
    });
	
	
	
});	//app.controller



/* 
传递给处理任务页的参数

@return doingTaskObj {String} 
*/
function setDoingTaskObj(taskObj) {
	var doingTaskObj = {
		"orderType": 2,
		"taskId": taskObj.taskId,
		"state": taskObj.state,
		"phoneOrder": taskObj.phoneOrder,
		"searchType": taskObj.searchType,
		"searchWord": taskObj.searchWord,
		"sellerNick": taskObj.sellerNick,		
		"searchTips": taskObj.searchTips,
		"imageTips": taskObj.imageTips,
		"stayTime": taskObj.stayTime,
		"productLink": taskObj.productLink,
		"talk": taskObj.talk,
		"qq": taskObj.qq,
		"buyerNick": taskObj.buyerNick,
		"rankLimit": taskObj.rankLimit,
		"browseFoot": taskObj.browseFoot,
		"compare": taskObj.compare,
		"collect": taskObj.collect,
		"collectShop": taskObj.collectShop,
		"browseCenter": taskObj.browseCenter,
		"lookRate": taskObj.lookRate,
		"lookSales": taskObj.lookSales,
		"browseOthers": taskObj.browseOthers,
	};
	return JSON.stringify(doingTaskObj);
}

/** 是否显示复制宝贝链接按钮 */
function proLinkIsShow(state, searchType) {
	if(searchType == 5) {
		return state > 101 ? true : false;
	} else {
		return state >= 320 ? true : false;
	}
}

/*
显示确认付款对话框
*/
function payDialog() {
	$("#payDialog").each(function(index, element) {
        $(element).remove();
    });
	var content = $("<div id='payDialog'></div>").load("doing-pay-dialog.html");
	var d = dialog({
			fixed: true,
			zIndex: 999999999,
    		title: '确认已付款',
  	  		content: content,
			okValue: '&nbsp;返&nbsp;回&nbsp;',
    		ok: function () {}
	});
	d.width(450);
	d.height(350);
	d.showModal();
}

/*
任务详情对话框
*/
function taskDetailDialog(content) {
	$("#taskDetailDialog").each(function(index, element) {
        $(element).remove();
    });
	var d = dialog({
			fixed: true,
			zIndex: 999999999,
    		title: '任务详情',
  	  		content: content,
			okValue: '返回',
    		ok: function () {}
	});
	d.width(800);
	d.height(450);
	d.showModal();
}

/*
查看评价晒图
*/
function ratePicDialog(content) {
	$("#ratePicDialog").each(function(index, element) {
        $(element).remove();
    });
	var d = dialog({
			fixed: true,
			zIndex: 999999999,
    		title: '评价晒图',
  	  		content: content,
			okValue: '返回',
    		ok: function () {}
	});
	d.width(600);
	d.height(400);
	d.showModal();
}

/*
复制宝贝链接
*/
function addZclip() {
	setTimeout(function() {
		 $(".copy-pro-link").each(function(index, element) {
			if($(element).siblings(".zclip").size() == 0) {
                Utils.appendZclip($(element), $(element).siblings("input")[0]);
			 }
		});
	}, 2000);
}
